package com.brush.framework.security.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.brush.common.core.domain.R;
import com.brush.common.utils.SecurityUtils;
import com.brush.common.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证失败处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        //有认证，令牌没有过期
        if (SecurityUtils.getAuthentication() != null && SecurityUtils.getAuthentication().isAuthenticated()) {
            int code = HttpStatus.HTTP_FORBIDDEN;
            String msg = StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
            R<Object> fail = R.fail(code, msg);
            // 输出信息给前端
            ServletUtils.renderString(response, JSONUtil.toJsonStr(fail));
        } else {
            //令牌无效了或过期了
            R<Object> fail = R.fail(401, "认证失败，请重新登录");
            ServletUtils.renderString(response, JSONUtil.toJsonStr(fail));
        }

    }
}
